export function buf2string(buffer) {
	const arr = Array.prototype.map.call(new Uint8Array(buffer), x => x)
	let str = ''
	for (let i = 0; i < arr.length; i ++) {
		str += String.fromCharCode(arr[i])
	}
	return str
}
// ArrayBuffer转16进度字符串示例
export function ab2hex(buffer) {
	const hexArr = Array.prototype.map.call(
		new Uint8Array(buffer),
		function (bit) {
			return ('00' + bit.toString(16)).slice(-2)
		}
	)
	return hexArr.join('')
}
// 将16进制的内容转成我们看得懂的字符串内容
export function hexCharCodeToStr(hexCharCodeStr) {
	const trimedStr = hexCharCodeStr.trim()
	const rawStr = trimedStr.substr(0, 2).toLowerCase() === '0x' ? trimedStr.substr(2) : trimedStr
	const len = rawStr.length
	if (len % 2 !== 0) {
		console.log('存在非法字符!')
		return ''
	}
	let curCharCode
	const resultStr = []
	for (var i = 0; i < len; i = i + 2) {
		curCharCode = parseInt(rawStr.substr(i, 2), 16)
		resultStr.push(String.fromCharCode(curCharCode))
	}
	return resultStr.join('')
}
export function sleep(ms) {
	return new Promise(resolve => setTimeout(resolve, ms));
}

// 字节转换整数
export function bytesToInt2(b) {
	let value = b[0] & 0xFF | (b[1] & 0xFF) << 8 | (b[2] & 0xFF) << 16 | (b[3] & 0xFF) << 24;
	if (value & 0x80000000) {
		value = -((~value & 0xFFFFFFFF) + 1);
	}
	return value;
}


export function HexString2Bytes(x) {
	const y = parseInt(x, 16) //十六进制转为十进制
	return y.toString(2).split('').map(item => Number(item)) //十进制转为2进制
}

export function stringToHex(str){
	let val = ''
	for(let i = 0; i < str.length; i++){
		if(val === '')
			val = str.charCodeAt(i).toString(16)
		else
			val += str.charCodeAt(i).toString(16)
	}
	return val
}

/* 防抖函数封装 */
export function debounce(fn, interval) {
	let timer;
	let delay = interval || 1000; // 间隔的时间，如果interval不传，则默认1秒
	return function () {
		let that = this;
		let args = arguments; // 保存此处的arguments，因为setTimeout是全局的，arguments不是防抖函数需要的。
		if (timer) {
			clearTimeout(timer);
		}
		timer = setTimeout(function () {
			fn.apply(that, args); // 用apply指向调用debounce的对象，相当于this.fn(args);
		}, delay);
	};
}

